<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2 class="cart-title">我的购物车</h2>
      <el-button 
        type="danger" 
        size="small" 
        @click="confirmClearCart" 
        :disabled="cartItems.length === 0"
      >
        清空购物车
      </el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading" size="30">
        <Loading />
      </el-icon>
      <span>加载中...</span>
    </div>

    <div v-else-if="cartItems.length === 0" class="empty-cart">
      <el-empty description="购物车空空如也，去挑选喜欢的美食吧~">
        <el-button type="primary" @click="goToProducts">去选购</el-button>
      </el-empty>
    </div>

    <div v-else class="cart-content">
      <div class="cart-items">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <div class="item-image">
            <img :src="getFullImageUrl(item.image)" :alt="item.name" />
          </div>
          
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div v-if="item.dishFlavor" class="item-flavor">
              <el-tag size="small" effect="plain">{{ formatFlavor(item.dishFlavor) }}</el-tag>
            </div>
          </div>
          
          <div class="item-price">¥{{ item.amount }}</div>
          
          <div class="item-quantity">
            <el-input-number 
              v-model="item.number" 
              :min="1" 
              :max="99" 
              size="small" 
              @change="(value) => updateItemCount(item, value)"
            />
          </div>
          
          <div class="item-subtotal">¥{{ (item.amount * item.number).toFixed(2) }}</div>
          
          <div class="item-actions">
            <el-button 
              type="danger" 
              size="small" 
              circle 
              @click="confirmDeleteItem(item)"
              :icon="Delete"
            />
          </div>
        </div>
      </div>
      
      <div class="cart-summary">
        <div class="summary-info">
          <div class="summary-row">
            <span>商品总数:</span>
            <span>{{ totalItems }} 件</span>
          </div>
          <div class="summary-row">
            <span>商品总价:</span>
            <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>
        
        <div class="checkout-actions">
          <el-button type="primary" size="large" @click="checkout" class="checkout-btn">
            去结算
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { Delete } from '@element-plus/icons-vue'
import { getCartList, updateCartItemCount, deleteCartItem, clearCart } from '@/api/cart'
import { fileViewPath } from '@/utils/file'

const router = useRouter()
const cartItems = ref([])
const loading = ref(false)

// 获取图片完整URL
const getFullImageUrl = (image) => {
  return fileViewPath + image
}

// 格式化口味信息
const formatFlavor = (flavor) => {
  try {
    const flavorObj = JSON.parse(flavor)
    return Object.entries(flavorObj)
      .map(([key, value]) => `${key}: ${value}`)
      .join(', ')
  } catch (e) {
    return flavor
  }
}

// 计算总价和总数量
const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.amount * item.number, 0)
})

const totalItems = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.number, 0)
})

// 获取购物车数据
const fetchCartItems = async () => {
  loading.value = true
  try {
    const res = await getCartList()
    if (res.code === '200') {
      cartItems.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取购物车数据失败')
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('获取购物车数据失败')
  } finally {
    loading.value = false
  }
}

// 更新购物车项数量
const updateItemCount = async (item, value) => {
  try {
    const data = {
      id: item.id,
      number: value
    }
    const res = await updateCartItemCount(data)
    console.log("data=",data)
    if (res.code !== '200') {
      ElMessage.error(res.msg || '更新数量失败')
      // 恢复原来的数量
      await fetchCartItems()
    }
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败')
    await fetchCartItems()
  }
}

// 删除购物车项
const confirmDeleteItem = (item) => {
  ElMessageBox.confirm(
    `确定要从购物车中移除 ${item.name} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteCartItem(item.id)
      if (res.code === '200') {
        ElMessage.success('删除成功')
        await fetchCartItems()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 清空购物车
const confirmClearCart = () => {
  ElMessageBox.confirm(
    '确定要清空购物车吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await clearCart()
      if (res.code === '200') {
        ElMessage.success('购物车已清空')
        cartItems.value = []
      } else {
        ElMessage.error(res.msg || '清空购物车失败')
      }
    } catch (error) {
      console.error('清空购物车失败:', error)
      ElMessage.error('清空购物车失败')
    }
  }).catch(() => {})
}

// 去结算
const checkout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品')
    return
  }
  router.push('/home/checkout')
}

// 跳转到商品页面
const goToProducts = () => {
  router.push('/home/products')
}

// 初始化
onMounted(() => {
  fetchCartItems()
})
</script>

<style scoped>
.cart-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  min-height: calc(100vh - 240px);
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.cart-title {
  font-size: 22px;
  color: #333;
  margin: 0;
  font-weight: 600;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.empty-cart {
  padding: 40px 0;
}

.cart-content {
  display: flex;
  flex-direction: column;
}

.cart-items {
  margin-bottom: 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 15px;
  border: 1px solid #f0f0f0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
  font-weight: 500;
}

.item-flavor {
  margin-top: 5px;
}

.item-price {
  width: 80px;
  font-size: 16px;
  color: #666;
  text-align: center;
}

.item-quantity {
  width: 120px;
  text-align: center;
}

.item-subtotal {
  width: 100px;
  font-size: 16px;
  color: #ff6b6b;
  font-weight: bold;
  text-align: center;
}

.item-actions {
  width: 60px;
  text-align: center;
}

.cart-summary {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-info {
  flex: 1;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 16px;
  color: #666;
}

.summary-row:last-child {
  margin-bottom: 0;
  font-size: 18px;
  color: #333;
}

.total-price {
  font-size: 24px;
  color: #ff6b6b;
  font-weight: bold;
}

.checkout-actions {
  margin-left: 20px;
}

.checkout-btn {
  background-color: #ff6b6b;
  border-color: #ff6b6b;
  font-size: 16px;
  padding: 12px 30px;
}

.checkout-btn:hover {
  background-color: #ff5252;
  border-color: #ff5252;
}

@media (max-width: 768px) {
  .cart-item {
    flex-wrap: wrap;
    padding: 15px 0;
  }
  
  .item-image {
    width: 60px;
    height: 60px;
  }
  
  .item-info {
    width: calc(100% - 75px);
  }
  
  .item-price, .item-quantity, .item-subtotal, .item-actions {
    margin-top: 10px;
    margin-left: 75px;
  }
  
  .item-price {
    width: 60px;
  }
  
  .item-quantity {
    width: 100px;
  }
  
  .item-subtotal {
    width: 80px;
  }
  
  .cart-summary {
    flex-direction: column;
  }
  
  .summary-info {
    margin-bottom: 15px;
    width: 100%;
  }
  
  .checkout-actions {
    margin-left: 0;
    width: 100%;
  }
  
  .checkout-btn {
    width: 100%;
  }
}
</style>